<template>
  <div class="review-container gradient-bg">
    <!-- 顶部导航 -->
    <header class="header glass">
      <el-button @click="$router.back()" text>
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
      <h2>{{ learning ? (currentMode === 'weak' ? '错题本' : '复习模式') : '复习中心' }}</h2>
      <div style="width: 100px"></div>
    </header>

    <!-- 模式选择卡片 -->
    <div class="mode-selector" v-if="!learning">
      <div class="mode-card glass" @click="startLearning('weak')">
        <div class="mode-icon">📕</div>
        <h3>错题本</h3>
        <p>复习掌握度低于60%的单词</p>
        <el-tag type="danger" size="large">{{ weakCount }} 个薄弱单词</el-tag>
      </div>
      <div class="mode-card glass" @click="startLearning('review')">
        <div class="mode-icon">📚</div>
        <h3>复习模式</h3>
        <p>根据记忆曲线智能复习</p>
        <el-tag type="warning" size="large">{{ reviewCount }} 个待复习单词</el-tag>
      </div>
    </div>

    <!-- 学习区域 -->
    <div class="learning-area" v-if="learning && currentWord">
      <!-- 进度条 -->
      <div class="progress-section">
        <span>{{ currentIndex + 1 }} / {{ words.length }}</span>
        <el-progress 
          :percentage="progress" 
          :show-text="false" 
          style="flex: 1; margin: 0 20px"
        />
        <el-tag :type="currentWord.mastery_level < 30 ? 'danger' : currentWord.mastery_level < 60 ? 'warning' : 'success'">
          掌握度: {{ currentWord.mastery_level }}%
        </el-tag>
      </div>

      <!-- 单词卡片 -->
      <div class="card-container">
        <div 
          class="word-card glass"
          :class="{ flipped: isFlipped }"
          @click="flipCard"
        >
          <!-- 正面 -->
          <div class="card-front">
            <div class="word-main">{{ currentWord.word }}</div>
            <div class="phonetic">{{ currentWord.phonetic }}</div>
            <el-button type="primary" size="large" @click.stop="speakWord" circle>
              <el-icon size="30"><Microphone /></el-icon>
            </el-button>
            <div class="hint">点击卡片查看中文</div>
            <!-- 学习记录 -->
            <div class="stats">
              <span class="stat-item correct">✓ {{ currentWord.correct_count || 0 }}</span>
              <span class="stat-item wrong">✗ {{ currentWord.wrong_count || 0 }}</span>
            </div>
          </div>

          <!-- 背面 -->
          <div class="card-back">
            <div class="chinese-main">{{ currentWord.chinese }}</div>
            <div class="word-secondary">{{ currentWord.word }}</div>
            <div class="unit-info">{{ currentWord.grade }} · {{ currentWord.unit }}</div>
            <div class="hint">点击卡片返回</div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="actions">
        <el-button 
          size="large" 
          class="action-btn wrong"
          @click="markWord(false)"
          :loading="submitting"
        >
          <el-icon><Close /></el-icon>
          还不熟练
        </el-button>
        <el-button 
          size="large"
          class="action-btn know"
          type="success"
          @click="markWord(true)"
          :loading="submitting"
        >
          <el-icon><Check /></el-icon>
          已经掌握
        </el-button>
      </div>
    </div>

    <!-- 空状态 -->
    <div class="empty-state glass" v-if="learning && !currentWord && !loading">
      <el-icon size="100" color="#67c23a"><CircleCheck /></el-icon>
      <h3>复习完成！</h3>
      <p>继续保持，明天再来吧~</p>
      <el-button type="primary" @click="backToDashboard">返回首页</el-button>
    </div>

    <!-- 加载状态 -->
    <div class="loading-state" v-if="loading">
      <el-icon class="is-loading" size="50"><Loading /></el-icon>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft, Microphone, Check, Close, CircleCheck, Loading } from '@element-plus/icons-vue'
import { vocabularyApi } from '@/api/vocabulary'
import type { Word } from '@/types'

const router = useRouter()

const currentMode = ref<'weak' | 'review'>('weak')
const learning = ref(false)
const loading = ref(false)
const words = ref<Word[]>([])
const currentIndex = ref(0)
const isFlipped = ref(false)
const submitting = ref(false)
const speaking = ref(false)
const weakCount = ref(0)
const reviewCount = ref(20) // 暂时写死，后续添加统计接口

const currentWord = computed(() => words.value[currentIndex.value])
const progress = computed(() => ((currentIndex.value + 1) / words.value.length) * 100)

let speechUtterance: SpeechSynthesisUtterance | null = null

// 开始学习
const startLearning = async (mode: 'weak' | 'review') => {
  currentMode.value = mode
  loading.value = true
  try {
    const api = mode === 'weak' ? vocabularyApi.getWeakWords : vocabularyApi.getReviewWords
    const res = await api(20)
    if (res.success && res.data) {
      words.value = res.data
      if (words.value.length === 0) {
        ElMessage.info(mode === 'weak' ? '暂无薄弱单词！太棒了！' : '暂无待复习单词！')
      } else {
        learning.value = true
        currentIndex.value = 0
        isFlipped.value = false
      }
    }
  } catch (error) {
    console.error('加载单词失败:', error)
    ElMessage.error('加载失败，请重试')
  } finally {
    loading.value = false
  }
}

// 加载统计
const loadStats = async () => {
  try {
    const res = await vocabularyApi.getWeakWords(100)
    if (res.success && res.data) {
      weakCount.value = res.data.length
    }
  } catch (error) {
    console.error('加载统计失败:', error)
  }
}

// 翻转卡片
const flipCard = () => {
  isFlipped.value = !isFlipped.value
}

// 朗读单词
const speakWord = () => {
  if (!speechSynthesis || !currentWord.value) return
  
  speaking.value = true
  speechSynthesis.cancel()
  
  speechUtterance = new SpeechSynthesisUtterance(currentWord.value.word)
  speechUtterance.lang = 'en-US'
  speechUtterance.rate = 0.8
  speechUtterance.pitch = 1
  
  speechUtterance.onend = () => {
    speaking.value = false
  }
  
  speechUtterance.onerror = () => {
    speaking.value = false
  }
  
  speechSynthesis.speak(speechUtterance)
}

// 标记单词
const markWord = async (know: boolean) => {
  if (!currentWord.value || submitting.value) return
  
  try {
    submitting.value = true
    const res = await vocabularyApi.recordProgress(currentWord.value.id, know)
    
    if (res.success) {
      ElMessage.success(know ? '很棒！继续加油~' : '多复习几次就能记住了！')
      
      // 进入下一个单词
      setTimeout(() => {
        if (currentIndex.value < words.value.length - 1) {
          currentIndex.value++
          isFlipped.value = false
        } else {
          // 复习完成
          learning.value = false
          ElMessage.success(`🎉 完成复习！`)
        }
      }, 1000)
    }
  } catch (error) {
    console.error('提交记录失败:', error)
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 返回首页
const backToDashboard = () => {
  router.push('/dashboard')
}

onMounted(() => {
  loadStats()
})

onUnmounted(() => {
  if (speechSynthesis) {
    speechSynthesis.cancel()
  }
})
</script>

<style scoped lang="scss">
.review-container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  
  h2 {
    color: white;
    margin: 0;
    font-size: 1.5rem;
  }
}

.mode-selector {
  flex: 1;
  display: flex;
  gap: 30px;
  padding: 40px;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.mode-card {
  width: 320px;
  padding: 40px 30px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-10px);
    box-shadow: 0 15px 40px rgba(102, 126, 234, 0.4);
  }
  
  .mode-icon {
    font-size: 5rem;
    margin-bottom: 20px;
  }
  
  h3 {
    color: white;
    font-size: 1.8rem;
    margin: 15px 0;
  }
  
  p {
    color: rgba(255, 255, 255, 0.8);
    margin-bottom: 20px;
    font-size: 1.1rem;
  }
}

.learning-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.progress-section {
  display: flex;
  align-items: center;
  gap: 10px;
  color: white;
  font-size: 1.1rem;
  font-weight: bold;
  margin-bottom: 20px;
  padding: 0 40px;
}

.card-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  perspective: 1000px;
}

.word-card {
  width: 500px;
  height: 450px;
  position: relative;
  transform-style: preserve-3d;
  transition: transform 0.6s;
  cursor: pointer;
  background: transparent !important;
  backdrop-filter: none !important;
  
  &.flipped {
    transform: rotateY(180deg);
  }
  
  &.flipped .card-front {
    visibility: hidden;
  }
  
  &.flipped .card-back {
    visibility: visible;
  }
}

.word-card .card-front,
.word-card .card-back {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
  -webkit-backface-visibility: hidden;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
  border-radius: 20px;
  overflow: hidden;
  box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.37);
  border: 1px solid rgba(255, 255, 255, 0.18);
}

.word-card .card-front {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  visibility: visible;
}

.word-card .card-front .word-main {
  font-size: 4rem;
  font-weight: bold;
  color: white;
  margin-bottom: 20px;
  text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.word-card .card-front .phonetic {
  font-size: 1.8rem;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 40px;
}

.word-card .card-front .hint {
  margin-top: 40px;
  color: rgba(255, 255, 255, 0.6);
  font-size: 1rem;
}

.word-card .card-front .stats {
  margin-top: 20px;
  display: flex;
  gap: 20px;
  
  .stat-item {
    font-size: 1.2rem;
    padding: 5px 15px;
    border-radius: 20px;
    
    &.correct {
      background: rgba(103, 194, 58, 0.3);
      color: #67c23a;
    }
    
    &.wrong {
      background: rgba(245, 108, 108, 0.3);
      color: #f56c6c;
    }
  }
}

.word-card .card-back {
  transform: rotateY(180deg);
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  visibility: hidden;
}

.word-card .card-back .chinese-main {
  font-size: 3.5rem;
  font-weight: bold;
  color: white;
  margin-bottom: 30px;
  text-shadow: 0 4px 10px rgba(0, 0, 0, 0.3);
}

.word-card .card-back .word-secondary {
  font-size: 2rem;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 20px;
}

.word-card .card-back .unit-info {
  font-size: 1.2rem;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 20px;
}

.word-card .card-back .hint {
  margin-top: 20px;
  color: rgba(255, 255, 255, 0.6);
}

.actions {
  display: flex;
  justify-content: center;
  gap: 30px;
  padding: 20px 40px;
}

.action-btn {
  min-width: 150px;
  height: 60px;
  font-size: 1.2rem;
  font-weight: bold;
  border-radius: 30px;
  
  &.wrong {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    border: none;
    color: white;
    
    &:hover {
      opacity: 0.9;
    }
  }
  
  &.know {
    background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  }
}

.empty-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  padding: 60px;
  margin: 40px;
  border-radius: 20px;
  
  h3 {
    color: white;
    font-size: 2rem;
    margin: 20px 0;
  }
  
  p {
    color: rgba(255, 255, 255, 0.7);
    font-size: 1.2rem;
    margin-bottom: 30px;
  }
}

.loading-state {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  
  p {
    margin-top: 20px;
    font-size: 1.2rem;
  }
}
</style>
